# from django.http import HttpResponse
from django.shortcuts import render
from analy.models import IMG
import os
import shutil
from myutils import guessImg_taobao
from myutils import GuessImgControl
from django.conf import settings
import json

def hello(request):
    context = {}
    context['hello'] = 'hello world !!! '
    return render(request, 'hello.html', context)

def uploadImg(request):
    if request.method == 'POST':
        new_img = IMG(
            img=request.FILES.get('img'),
            name=request.FILES.get('img').name[-20:]
        )
        new_img.save()
        want = request.POST['want']
        print("want=",want)

        imgname = request.FILES.get('img').name
        imgpath = os.path.join(settings.MEDIA_ROOT, r'img',imgname)
        print('name = %s path = %s' %(imgname,imgpath))

        # result = {"guessWord":"","details":""}
        result={"data":""}
        if want == 'zhe shi na' or want == 'zhe shi shui' or want == 'zhe shi shen me':

            # 暂时设置10s超时
            gc = GuessImgControl.GsCtrl()
            re = gc.getGuessWord(imgname,imgpath,10)
            if re:
                # result["data"] = re
                result["data"] = json.dumps(re,ensure_ascii=False)
        elif want == 'tao bao tong kuan':
            gimg = guessImg_taobao.TaoLiPaiGuessImg(imgname,imgpath)
            # result["data"] = gimg.tryGuess()
            result["data"] = json.dumps(gimg.tryGuess(),ensure_ascii=False)
        
        return render(request, 'uploadimg.html',result)
    else:
        return render(request,'uploadimg.html')

def showImg(request):
    imgs = IMG.objects.all()
    content = {
        'imgs': imgs,
    }
    for img in imgs:
        print(img.img.url)
    return render(request, 'showing.html', content)

def deleteImg(request):
    print('delete all img')
    # 删除数据库数据
    IMG.objects.all().delete()
    # 删除图片文件
    imgfod = os.path.join(settings.MEDIA_ROOT, r'img')
    shutil.rmtree(imgfod)
    os.mkdir(imgfod)
    return render(request, 'showing.html', {})

